/*
 * xiao
 * 2018.9.29
 * 1.实名认证
 */
mui.init();
var mask = mui.createMask(); //遮罩层
var my_phone = localStorage.getItem("my_phone");
var user_id = localStorage.getItem("user_id");
var realname, certificates, city, front_photo, handheld_according; //全局变量
//实名认证
$(document).on("tap", ".sure_btn", function() {
	realname = $("#name").val(); //名字
	city = $("#address").text(); //地区
	certificates = $("#certificates").val(); //证件
	front_photo = $("#shop_front_img").attr("img_url"); //身份证正面照
	handheld_according = $("#store_panorama_img").attr("img_url"); //手持照
	if(!realname) {
		mui.toast("请输入姓名");
		return false;
	}
	if(!certificates) {
		mui.toast("请输入证件号");
		return false;
	}
	if(city == "中国") {
		certification();
	} else {
		if(!front_photo) { //判断店铺正面照是否为空
			mui.toast("必须上传身份证正面照")
			return;
		}
		if(!handheld_according) { //判断店铺正面照是否为空
			mui.toast("必须手持身份证照")
			return;
		}
		plus.nativeUI.showWaiting("加载中...");
		mask.show(); //显示遮罩层
		authentication_haiwai();
	}

})

//验证实名接口
function certification() {
	plus.nativeUI.showWaiting("加载中...");
	mask.show(); //显示遮罩层
	mui.ajax(user_url + '/api/certification', {
		data: {
			"identity": certificates,
			"phone": my_phone,
			"realname": realname,
			"sign": "string",
			"user_id": user_id
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		headers: {
			'Content-Type': 'application/json'
		},
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			//console.log(JSON.stringify(data));
			if(data.code == 10000) {
				authentication();
			} else {
				mui.toast(data.msg);
				plus.nativeUI.closeWaiting(); //关闭等待
				mask.close(); //关闭遮罩层
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			plus.nativeUI.closeWaiting(); //关闭等待
			mask.close(); //关闭遮罩层
			console.log(type);
			var error_msg = JSON.parse(xhr.responseText)
			mui.alert(error_msg.msg)
		}
	})

}

//国内实名认证接口
function authentication() {
	mui.ajax(user_url + '/api/authentication', {
		data: {
			"identity": certificates,
			"phone": my_phone,
			"realname": realname,
			"sign": "string",
			"user_id": user_id
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		headers: {
			'Content-Type': 'application/json'
		},
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			if(data.code == 10000) {
				plus.nativeUI.closeWaiting(); //关闭等待
				mask.close(); //关闭遮罩层
				mui.toast("实名认证成功");
				window.top.location.href = "my_user.html"
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			plus.nativeUI.closeWaiting(); //关闭等待
			mask.close(); //关闭遮罩层
			console.log(type);
			var error_msg = JSON.parse(xhr.responseText)
			mui.alert(error_msg.msg);

		}
	})
}

//海外认证接口
function authentication_haiwai() {
	mui.ajax(user_url + '/api/authentication', {
		data: {
			"identity": certificates,
			"phone": my_phone,
			"realname": realname,
			"sign": "string",
			"area": city,
			"front_photo": front_photo,
			"handheld_according": handheld_according,
			"type": 2,
			"user_id": user_id
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		headers: {
			'Content-Type': 'application/json'
		},
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			if(data.code == 10000) {
				plus.nativeUI.closeWaiting(); //关闭等待
				mask.close(); //关闭遮罩层
				mui.toast("申请成功，等待审核");
				window.top.location.href = "my_user.html"
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			plus.nativeUI.closeWaiting(); //关闭等待
			mask.close(); //关闭遮罩层
			console.log(type);
			var error_msg = JSON.parse(xhr.responseText)
			mui.alert(error_msg.msg);

		}
	})
}

//页面进入执行方法
window.onload = function() {
	mui.plusReady(function() {
		var self = plus.webview.currentWebview();
		isAuthentication();
	});
}

//查询用户有无实名过，有则把信息填到对应标签
function isAuthentication() {
	mui.ajax(user_url + '/api/isAuthentication', {
		data: {
			"phone": my_phone,
			"sign": "string",
			"user_id": user_id
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		headers: {
			'Content-Type': 'application/json'
		},
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			if(data.code == 10000) {
				if(data.resp) {
					console.log(JSON.stringify(data))
					$("#address").text(data.resp.area); //地区
					$("#name").val(data.resp.realname); //姓名
					$("#certificates").val(data.resp.identity); //证件号 ss
					$("#store_img_one").attr("src", data.resp.url + data.resp.front_photo); //正面照
					$("#shop_front_img").attr("img_url", data.resp.front_photo); //身份证正面照
					$("#store_img_tow").attr("src", data.resp.url + data.resp.handheld_according); //手持照
					$("#store_panorama_img").attr("img_url", data.resp.handheld_according); //手持照
					hidden(); //
				}
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(type);
			var error_msg = JSON.parse(xhr.responseText)
			mui.toast(error_msg.msg);
		}
	})

}

var text;
(function($, doc) {
	$.init();
	$.ready(function() {
		var _getParam = function(obj, param) {
			return obj[param] || '';
		};
		//普通示例
		var userPicker = new $.PopPicker();
		userPicker.setData([{
			value: 'China',
			text: '中国'
		}, {
			value: 'taiwan',
			text: '台湾'
		}, {
			value: 'xianggang',
			text: '香港'
		}, {
			value: 'aomen',
			text: '澳门'
		}, {
			value: 'mlxy',
			text: '马来西亚'
		}]);
		var showUserPickerButton = doc.getElementById('address'); //选择器
		var userResult = doc.getElementById('address'); //地址
		showUserPickerButton.addEventListener('tap', function(event) {
			userPicker.show(function(items) {
				text = JSON.stringify(items[0].text).replace(/\"/g, "");
				userResult.innerText = text;
				hidden();
				//返回 false 可以阻止选择框的关闭
				//return false;
			});
		}, false);
	});
})(mui, document);

function hidden() {
	var address = $("#address").text();
	if(address == "中国") {
		$("#hidden").css("display", "none")
	} else {
		$("#hidden").css("display", "block")
	}
}

//点击上传图片按钮
mui('body').on('tap', '.hhhh', function() {
	a = $(this);
	getImg(a);
});
//点击事件，弹出选择摄像头和相册的选项
function getImg(a) {
	var bts = [{
		title: "拍照"
	}, {
		title: "从相册选择"
	}];
	plus.nativeUI.actionSheet({
			cancel: "取消",
			buttons: bts
		},
		function(e) {
			if(e.index == 1) {
				getImage(a);
			} else if(e.index == 2) {
				galleryImgs(a);
			}
		}
	);
}

//调用手机摄像头并拍照
function getImage(a) {
	var cmr = plus.camera.getCamera();
	cmr.captureImage(function(p) {
		// alert('拍照'+p)
		plus.io.resolveLocalFileSystemURL(p, function(entry) {
			compressImage(entry.toLocalURL(), entry.name);
			var img = a.find(".store_img"); //图片位置
			img.attr("src", entry.toLocalURL());
		}, function(e) {
			plus.nativeUI.toast("读取拍照文件错误：" + e.message);
		});
	}, function(e) {}, {
		filter: 'image'
	});
}

//从相册选择照片
function galleryImgs(a) {
	plus.gallery.pick(function(e) {
		// alert(e)
		var name = e.substr(e.lastIndexOf('/') + 1);
		compressImage(e, name);
		var img = a.find(".store_img"); //图片位置
		img.attr("src", e);
	}, function(e) {}, {
		filter: "image"
	});
}

//压缩图片
function compressImage(url, filename) {
	var name = "_doc/upload/" + filename;
	plus.zip.compressImage({
			src: url, //src: (String 类型 )压缩转换原始图片的路径
			dst: name, //压缩转换目标图片的路径
			quality: 30, //quality: (Number 类型 )压缩图片的质量.取值范围为1-100
			overwrite: true //overwrite: (Boolean 类型 )覆盖生成新文件
		},
		function(zip) {
			console.log('图片压缩后路径' + zip.target)
			createUpload(zip.target)
		},
		function(error) {
			plus.nativeUI.toast("压缩图片失败，请稍候再试");
		});
}

//上传图片
function createUpload(url) {
	//服务器地址
	var server = user_url + "/open/upload";
	var wt = plus.nativeUI.showWaiting();
	var task = plus.uploader.createUpload(server, {
			method: "POST"
		},
		function(t, status) { //上传完成
			if(status == 200) {
				mui.toast("上传成功");
				var headimg = JSON.parse(t.responseText)
				var headImgUrl = headimg.data;
				a.attr('img_url', headImgUrl);
				wt.close(); //关闭等待提示按钮
			} else {
				mui.toast("上传失败：" + status);
				wt.close(); //关闭等待提示按钮
			}
		}
	);
	//将文件添加到上传队列中
	task.addFile(url, {
		key: 'file'
	});
	task.start();
}